const { defineConfig } = require('@vue/cli-service')
const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

// 判断是否是生产环境
const isProduction = process.env.NODE_ENV === 'production'

module.exports = defineConfig({
  transpileDependencies: true,
  
  // 生产环境相关的配置
  // publicPath: process.env.NODE_ENV === 'production' ? '/your-app/' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  // 生产环境下关闭sourcemap以减少包大小
  productionSourceMap: false,

  
// 配置Webpack
  configureWebpack: config => {
    if (isProduction) {
      // 生产环境特定配置
      config.optimization = {
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            elementUI: {
              name: 'chunk-element-ui',
              priority: 20,
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/
            },
            commons: {
              name: 'chunk-commons',
              test: /[\\/]src[\\/]components[\\/]/,
              minChunks: 3,
              priority: 5,
              reuseExistingChunk: true
            }
          }
        }
      }
      
      // 添加压缩插件
      config.plugins.push(
        new CompressionPlugin({
          algorithm: 'gzip',
          test: /\.(js|css|html|svg)$/,
          threshold: 10240,
          minRatio: 0.8
        })
      )
      
      // 可选：包分析工具（只在需要分析时启用）
      if (process.env.USE_ANALYZER) {
        config.plugins.push(new BundleAnalyzerPlugin())
      }
    }
  },
  
 
  
  //开发服务器配置（生产环境不需要，但保留供参考）
  devServer: {
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_BASE_URL,
        changeOrigin: true,
        pathRewrite: { '^/api': '' }, // 可选：去掉 /api 前缀
      }
    }
  }
})